package com.jt.assistant

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.TextUtils
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.cl.picture_selector.ImagePicker
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.custom_view.ItemEdit
import com.jt.assistant.ui.PreActivity
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.utils.ImageUtil
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.base.GlobalConfig.MSG_SPEAK
import com.orhanobut.logger.Logger
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import com.yzp.mvvmlibrary.base.BaseActivity
import com.yzp.mvvmlibrary.base.MessageEvent
import com.yzp.mvvmlibrary.base.NoViewModel
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.*

class MainActivity : BaseActivity<NoViewModel>() {
    private val REQUEST_SELECT_IMAGES_CODE = 0x01
    private var mImagePaths: ArrayList<String>? = ArrayList<String>()
    private var mTextToSpeech: TextToSpeech? = null
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        ImageUtil.deleteCompressPic(mImagePaths!!)
        super.onDestroy()
    }

    override fun layoutId(): Int = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        with(rv_pic) {
            layoutManager = GridLayoutManager(context, 3)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
        bestPermissionX()
        initSpeech()


        item_edit.setEditText("的撒娇地哦啊基调")

        val data = ArrayList<String>()

        data.add("大飒飒是发生的方式")
        data.add("大飒飒是发生的方式")
        data.add("大飒飒是发生的方式")

        item_edit.mEdit.setOnClickListener {
            item_edit.showListDialog("测试对话框", this)
        }


        item_edit.setOnItemClickListener(object : ItemEdit.OnClickLister {
            override fun onItemClick(position: Int) {
                ToastUtils.showShort(data[position])
            }
        })
//        startActivityForResult(Intent(this@MainActivity, DecodeActivity::class.java), 1000)

    }


    override fun initListener() {

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == (mAdapter.itemCount - 1)) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(9 - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@MainActivity,
                        REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(Intent(this@MainActivity, PreActivity::class.java).apply {
                    putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                    putExtra("POSITION", position)
                }, GlobalConfig.PIC_REQUEST)
            }

        }


        tv_test.setOnClickListener {

        }
    }

    private fun scanResult(requestCode: Int, result: String?) {
        if (requestCode == 1000) tv_test.text = result
    }

    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    tv_test.text = file.absolutePath + tv_test.text
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                }

                override fun onError(e: Throwable) {

                }
            }).launch()
    }

    private fun initSpeech() {
        mTextToSpeech = TextToSpeech(
            applicationContext
        ) { status ->
            if (status == TextToSpeech.SUCCESS) {
                val result: Int = mTextToSpeech!!.setLanguage(Locale.CHINA)
                if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED
                ) {
                    ToastUtils.showShort("请升级语音引擎,详情请联系管理员")
                }
            }
        }
        mTextToSpeech!!.setPitch(1.0f)
        mTextToSpeech!!.setSpeechRate(1.4f)
    }


    private fun speak(text: String?) {
        if (mTextToSpeech != null) {
            mTextToSpeech!!.stop()
            mTextToSpeech!!.speak(text, TextToSpeech.QUEUE_FLUSH, null)
            ToastUtils.showShort(text)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun message(messageEvent: MessageEvent) {
        if (messageEvent.type === MSG_SPEAK) {
            speak(messageEvent.msg)
//            ToastUtils.showShort(messageEvent.msg)
        }
    }


    private fun bestPermissionX() {
        PermissionX.init(this)
            .permissions(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String?>? ->
                val message = "PermissionX需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
            }
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?> ->
                if (allGranted) {
                } else {
                    Toast.makeText(this, "您拒绝了如下权限：$deniedList", Toast.LENGTH_SHORT).show()
                }
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (data != null) {
                //获取扫描结果
                val bundle = data.extras
                val result = bundle!!.getString("EXTRA_STRING")
                scanResult(requestCode, result)
            }
        }

        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            mImagePaths = data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES)
            imagePick(mImagePaths)
        }
    }


}